package com.abe.bathsystem.android.v3;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.view.View;

import com.abe.bathsystem.base.ManagerAPP;
import com.abe.bathsystem.base.ManagerLocalData;
import com.abe.bathsystem.base.ManagerTimer;
import com.abe.bathsystem.entity.ReqConstant;
import com.abe.bathsystem.entity.http.HttpAdEntity;
import com.abe.bathsystem.entity.http.HttpNoticeEntity;
import com.abe.bathsystem.entity.http.HttpRoomEntity;
import com.abe.bathsystem.widget.dialog.ShowNoticeDialog;
import com.abe.bathsystem.widget.text.LooperTextView;
import com.abe.bathsystem.widget.video.AdVideoAutoPlayer;
import com.abe.libcore.utils.normal.CommonUtils;
import com.abe.libcore.utils.normal.EmptyUtils;
import com.abe.libcore.utils.normal.ThreadPoolUtils;
import com.bumptech.glide.Glide;
import com.maning.mndialoglibrary.MProgressDialog;

import net.yet.campusdev.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import cn.jzvd.JZMediaManager;
import cn.jzvd.JZVideoPlayerStandard;

public abstract class MainBathAdActivity extends MainBathSetActivity implements AdVideoAutoPlayer.OnVideoPlayListener {
    //通知滚动播放
    protected List<String> notices = new ArrayList<>();
    //播放相关
    protected List<HttpAdEntity> medias = new ArrayList<>();
    protected int playCount = -1;
    //当前广告
    protected HttpAdEntity adEntity;
    //当前多媒体文件播放时间
    protected int currentMediaPlayTime = ManagerTimer.IMAGE_PLAY_TIME;
    protected Bitmap coverBitmap = null;
    //定时取广告数据
    private Timer timer;
    private TimerTask task;
    private int timeOutAdNum = 0;
    private int mediaPlayCount = 0;

    //计时共享到Control
    public abstract void timerTaskControlRun();

    @Override
    public void initContent() {
        super.initContent();
        setControlGone();
        //遮盖层
        Glide.with(this).load(R.drawable.icon_welcome).centerCrop().into(itemAdCover);
        Glide.with(this).load(R.drawable.icon_trans).centerCrop().into(itemAdImage);
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    private void showMedia() {
        if (medias == null || medias.size() == 0) {
            Glide.with(this).load(R.drawable.icon_test_main_show).centerCrop().into(itemAdCover);
            return;
        }
        playCount++;
        int mediaCount = playCount % medias.size();
        adEntity = medias.get(mediaCount);
        //根据广告类型，切换显示方式
        switch (adEntity.getAdType()) {
            case ReqConstant.AD_TYPE_IMG: {
                Glide.with(this).load(R.drawable.drawable_ad_cover).into(itemAdCover);
                Glide.with(this).load(adEntity.getUrl()).centerCrop().into(itemAdImage);
            }
            break;
            case ReqConstant.AD_TYPE_VIDEO: {
                showVideo(adEntity.getUrl());
                ThreadPoolUtils.execute(new CheckUrlThread());
            }
            break;
        }
    }

    //播放视频
    private void showVideo(String url) {
        itemAdVideo.setUp(url, JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
        itemAdVideo.setPlayListener(this);
        itemAdVideo.startButton.performClick();
        setControlGone();
    }

    private void setControlGone() {
        itemAdVideo.setAllControlsVisiblity(View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE, View.GONE);
    }

    @Override
    public void onVideoPrepare() {

    }

    @Override
    public void onVideoStart() {
        Glide.with(this).load(R.drawable.icon_trans).centerCrop().into(itemAdCover);
        Glide.with(this).load(R.drawable.icon_trans).centerCrop().into(itemAdImage);
    }

    @Override
    public void onVideoPlay() {
        Glide.with(this).load(R.drawable.icon_trans).centerCrop().into(itemAdCover);
        Glide.with(this).load(R.drawable.icon_trans).centerCrop().into(itemAdImage);
    }

    @Override
    public void onVideoError() {
        if (adEntity.getAdType() == ReqConstant.AD_TYPE_VIDEO) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showMedia();
                }
            });
            mediaPlayCount = 0;
        }
    }

    @Override
    public void onVideoPause() {

    }

    @Override
    public void onStateAutoComplete() {

    }

    @Override
    public void onAutoCompletion() {
        //获取视频当前帧来作为播放下一个视频的缓冲界面
        coverBitmap = JZMediaManager.textureView.getBitmap();
        itemAdImage.setImageBitmap(coverBitmap);
        //下一个
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showMedia();
            }
        });
        mediaPlayCount = 0;
    }

    @Override
    protected void onPause() {
        super.onPause();
        //当activity不在前台是停止定时
        stopTimer();
    }

    @Override
    public void onDestroy() {
        //清理视频切换缓冲图片
        if (coverBitmap != null) {
            coverBitmap.recycle();
            coverBitmap = null;
        }
        if (EmptyUtils.isNotEmpty(itemAdVideo)) {
            itemAdVideo.release();
        }
        stopTimer();
        destroyTimer();
        super.onDestroy();
    }

    @Override
    public void onAdData(List<HttpAdEntity> entity) {
        medias.clear();
        medias.addAll(entity);
        playCount = -1;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showMedia();
            }
        });
    }

    @Override
    public void onNoticeData(final List<HttpNoticeEntity> entities) {
        if (entities.size() <= 0) {
            return;
        }
        this.notices.clear();
        for (int i = 0; i < entities.size(); i++) {
            if (!TextUtils.isEmpty(entities.get(i).getBody())) {
                notices.add(entities.get(i).getBody());
            }
        }
        itemTxtGg.setTipList(notices);
        itemTxtGg.setListener(new LooperTextView.OnChoosePosListener() {
            @Override
            public void onChoose(int pos) {
                if (pos >= 0 && pos < notices.size()) {
                    HttpNoticeEntity noticeEntity = entities.get(pos);
                    showNoticeDialog = new ShowNoticeDialog(MainBathAdActivity.this,
                            MainBathAdActivity.this, noticeEntity);
                    showNoticeDialog.show();
                }
            }
        });
        //列表展示(组装数据)
        looperNoticeEntities.clear();
        looperNoticeEntities.add(entities);
        switch (entities.size()) {
            case 1:
                break;
            case 2: {
                List<HttpNoticeEntity> entities1 = new ArrayList<>();
                entities1.add(entities.get(1));
                looperNoticeEntities.add(entities1);
            }
            break;
            default: {
                List<HttpNoticeEntity> entities1 = new ArrayList<>();
                List<HttpNoticeEntity> entities2 = new ArrayList<>();
                for (int i = 0; i < entities.size(); i++) {
                    if (i > 0) {
                        entities1.add(entities.get(i));
                    }
                    if (i > 1) {
                        entities2.add(entities.get(i));
                    }
                }
                entities1.add(entities.get(0));
                entities2.add(entities.get(0));
                entities2.add(entities.get(1));
                looperNoticeEntities.add(entities1);
                looperNoticeEntities.add(entities2);
            }
            break;
        }
        noticeAdapter.notifyDataSetChanged();
    }

    //启动计时器
    private void startTimer() {
        /*
         * java.util.Timer.schedule(TimerTask task, long delay, long period)：
         * 这个方法是说，delay/1000秒后执行task,然后进过period/1000秒再次执行task，
         * 这个用于循环任务，执行无数次，当然，你可以用timer.cancel();取消计时器的执行。
         */
        timer = new Timer();
        task = new ShowTimeOutTask();
        try {
            timer.schedule(task, 1000, 1000);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            timer = new Timer();
            task = new ShowTimeOutTask();
            timer.schedule(task, 1000, 1000);
        }
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
        }
        //置零
        timeOutAdNum = 0;
    }

    private void destroyTimer() {
        timer = null;
        task = null;
    }

    protected class ShowTimeOutTask extends TimerTask {


        @Override
        public void run() {
            timerTaskUploadClientRun();
            timerTaskControlRun();
            timeOutAdNum++;
            //开启洗浴显示加载框
            if (MProgressDialog.isShowing()) {
                timeOutDialogShow++;
                if (timeOutDialogShow > READ_TIME_OUT) {
                    timeOutDialogShow = 0;
                    MProgressDialog.dismissProgress();
                }
            } else {
                timeOutDialogShow = 0;
            }
            Date nowDate = getRealTime();
            //30分钟自动提交，每分钟检查
            String nowDateStr = new SimpleDateFormat("ss", Locale.CHINA).format(nowDate);
            if (nowDateStr.equals("00")) {
                //秒为00，即每分钟检查
                ThreadPoolUtils.execute(new CheckAllThread());
                //12:20之后自动提交所有
                Date cutAll = getCutAllTime(nowDate);
                Date cutEnd = getEndCutTime(nowDate);
                if (nowDate.getTime() > cutAll.getTime() && nowDate.getTime() < cutEnd.getTime()) {
                    HttpRoomEntity roomEntity = ManagerLocalData.getRoomData();
                    if (roomEntity != null)
                        ThreadPoolUtils.execute(new SubmitAll(roomEntity));
                }
            }
            //多媒体展示
            if (medias != null && medias.size() != 0) {
                mediaPlayCount++;
                if (adEntity.getAdType() == ReqConstant.AD_TYPE_IMG) {
                    if (mediaPlayCount >= currentMediaPlayTime) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showMedia();
                            }
                        });
                        mediaPlayCount = 0;
                    }
                }
            }
            //服务信息获取
            if (isGetServerDataSuccess) {
                //获取成功后，每隔固定时间重新获取房间信息
                if (timeOutAdNum * 1000 >= ManagerTimer.adUpdateTime()) {
                    timeOutAdNum = 0;
                    CommonUtils.sendLocalBroadcast(ManagerAPP.RESET_PUSH_SERVICE);
                    serverPresenter().getServerData();
                }
            } else {
                //获取失败后，每隔5秒重新获取一次
                if (timeOutAdNum % 5 == 0) {
                    serverPresenter().getServerData();
                }
            }
        }
    }

    //30分钟自动提交功能
    class CheckAllThread implements Runnable {

        @Override
        public void run() {
            submitTimeOut30();
        }
    }


    //检查视频Url是否可用
    class CheckUrlThread implements Runnable {

        @Override
        public void run() {
            try {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(adEntity.getUrl(), new HashMap<String, String>());
                if (adEntity.getAdType() == ReqConstant.AD_TYPE_VIDEO) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showMedia();
                        }
                    });
                    mediaPlayCount = 0;
                }
            } catch (Exception e) {
                CommonUtils.w("CheckUrlThread-Exception:" + e.getMessage());
                e.printStackTrace();
                if (adEntity.getAdType() == ReqConstant.AD_TYPE_VIDEO) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showMedia();
                        }
                    });
                    mediaPlayCount = 0;
                }
            }
        }
    }
}